package net.expectx.pay.controller.merchant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConfig;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseConstants;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.util.ImageUtil;
import net.expectx.pay.common.AdminConstants;
import net.expectx.pay.common.AdminResult;
import net.expectx.pay.common.BaseController;
import net.expectx.pay.common.util.WXPayConfigImpl;
import net.expectx.pay.core.common.EXPayResult;
import net.expectx.pay.core.micro.WeiXinMicroBo;
import net.expectx.pay.core.micro.WeiXinMicroMerchantServicesUtil;
import net.expectx.pay.dao.bean.*;
import net.expectx.pay.rpc.api.MerchantOauthService;
import net.expectx.pay.rpc.api.MerchantUserService;
import net.expectx.pay.rpc.api.MerchantWeixinSignService;
import net.expectx.pay.rpc.api.SystemTypeGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 2018/09/06
 *
 * @author Rui
 */
@Controller
@RequestMapping(value = "/manager/merchant/oauth")
public class MerchantOauthController extends BaseController {

    @Autowired
    private SystemTypeGroupService systemTypeGroupService;
    @Autowired
    private MerchantOauthService merchantOauthService;
    @Autowired
    private MerchantUserService merchantUserService;
    @Autowired
    private MerchantWeixinSignService merchantWeixinSignService;

    @ApiOperation(value = "认证主页")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "merchant/oauth/index";
    }

    @ApiOperation(value = "认证主页")
    @RequestMapping(value = "/payOauth/{id}", method = RequestMethod.GET)
    public String payOauth(@PathVariable("id") Long id, ModelMap modelMap) {
        modelMap.put("id", id);
        MerchantOauth merchantOauth=merchantOauthService.selectByPrimaryKey(id);
        String merchantNo=merchantUserService.selectByPrimaryKey(merchantOauth.getMerchantUserId()).getMerchantNo();
        MerchantWeixinSignExample merchantWeixinSignExample=new MerchantWeixinSignExample();
        merchantWeixinSignExample.createCriteria().andMerchantNoEqualTo(merchantNo).andBusinessCodeEqualTo(merchantOauth.getBusinessCode());
        List<MerchantWeixinSign>merchantWeixinSigns=merchantWeixinSignService.selectByExample(merchantWeixinSignExample);
        if (merchantWeixinSigns.isEmpty()){
            modelMap.put("isSubmit", false);
        }else{
            modelMap.put("isSubmit", true);
            modelMap.put("signRecord", merchantWeixinSigns.get(0));
        }
        return "merchant/oauth/payOauth";
    }

    @ApiOperation(value = "认证")
    @RequestMapping(value = "/oauth/{id}", method = RequestMethod.GET)
    public String oauth(@PathVariable("id") Long id, ModelMap modelMap,HttpServletRequest request) {
        MerchantUser merchantUser = merchantUserService.selectByPrimaryKey(id);
        MerchantOauthExample merchantOauthExample = new MerchantOauthExample();
        MerchantOauthExample.Criteria criteria = merchantOauthExample.createCriteria();
        criteria.andMerchantUserIdEqualTo(merchantUser.getId());
        List<MerchantOauth> merchantOauthList = merchantOauthService.selectByExample(merchantOauthExample);
        if (!merchantOauthList.isEmpty()) {
            MerchantOauth merchantOauth = merchantOauthList.get(0);
            modelMap.put("merchantOauth", merchantOauth);
            request.setAttribute("status",merchantOauth.getStatus());

    }
        return "merchant/oauth/oauth";
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Object page(
            @RequestParam(required = false, defaultValue = "1", value = "page") int page,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(16);

        String typeGroupName = request.getParameter("typeGroupName");
        MerchantUserExample merchantUserExample = new MerchantUserExample();
        /**
         * 创造条件
         */
        MerchantUserExample.Criteria criteria = merchantUserExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        /**
         * 分页
         */
        merchantUserExample.setPageIndex(page);
        merchantUserExample.setPageSize(limit);
        /**
         * 排序
         */
        merchantUserExample.setOrderByClause("gmt_modified desc");

        List<MerchantUser> merchantOauths = merchantUserService.selectByExample(merchantUserExample);
        long total = merchantUserService.countByExample(merchantUserExample);
        result.put("code", AdminConstants.LAYUI_DATA_OK);
        result.put("count", total);
        result.put("msg", "");
        result.put("data", merchantOauths);
        return result;
    }

    @ApiOperation(value = "审核")
    @RequestMapping(value = "/oauth/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object oauth(@PathVariable("id") Long id, Long merchantUserId, String oauthRemark,HttpServletRequest request) {
        MerchantUser merchantUser = merchantUserService.selectByPrimaryKey(merchantUserId);
        MerchantOauth merchantOauth = merchantOauthService.selectByPrimaryKey(id);
        merchantOauth.setStatus(Byte.valueOf("1"));

        request.setAttribute("status","0");

        merchantOauth.setOauthRemark("");
        merchantUser.setIsAuth(BaseConstants.YES);
        if (null != oauthRemark) {
            merchantOauth.setStatus(Byte.valueOf("3"));

            merchantUser.setIsAuth(Byte.valueOf("0"));
            merchantOauth.setOauthRemark(oauthRemark);
        }
        BaseResult baseResult = merchantUserService.updateByPrimaryKeySelective(merchantUser);
        if (baseResult.isSuccess()) {
            return merchantOauthService.updateByPrimaryKeySelective(merchantOauth);
        }
        return baseResult;
    }

       @ApiOperation(value = "提交微信/支付宝/银联审核")
    @RequestMapping(value = "/{id}/{type}/oauth", method = RequestMethod.POST)
    @ResponseBody
    public Object oauth(@PathVariable("id") Long id, @PathVariable("type") Integer type, HttpServletRequest request) throws Exception {
        WXPayConfig wxPayConfig = WXPayConfigImpl.getInstance();

        MerchantOauth merchantOauth = merchantOauthService.selectByPrimaryKey(id);
        String savePath = request.getSession().getServletContext().getRealPath(
                "/")
                + "/upload/micro/oauth/" + merchantOauth.getMerchantUserId() + "/";
        File tempDirPath = new File(savePath);
        if (!tempDirPath.exists()) {
            tempDirPath.mkdirs();
        }
        System.out.println(savePath);
        if (1 == type) {
            BaseResult baseResult=doWeiXinMicroSubmit(merchantOauth, savePath, wxPayConfig);
           //  FileUtils.deleteDirectory(new File(savePath));
            return baseResult;
        } else {
            return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "还未开通此方式得认证", null);
        }
    }

    /**
     * 使用申请入驻接口提交你的小微商户资料
     *
     * @param merchantOauth
     * @return
     */
    public AdminResult doWeiXinMicroSubmit(MerchantOauth merchantOauth, String savePath, WXPayConfig wxPayConfig) {
        try {
            EXPayResult imageResult= WeiXinMicroMerchantServicesUtil.uploadWxPicture(ImageUtil.downloadPicture(merchantOauth.getLegalPersonIdentificationPortrait(), savePath));
            if (!imageResult.isSuccess()){
                return  new AdminResult(imageResult);
            }
            merchantOauth.setLegalPersonIdentificationPortrait(imageResult.getData().toString());

            imageResult=WeiXinMicroMerchantServicesUtil.uploadWxPicture(ImageUtil.downloadPicture(merchantOauth.getLegalPersonIdCardNationalEmblem(), savePath));
            if (!imageResult.isSuccess()){
                return  new AdminResult(imageResult);
            }
            merchantOauth.setLegalPersonIdCardNationalEmblem(imageResult.getData().toString());

            String idCardValidStartTime="";
            String idCardValidEndTime="";
            String legalPersonValidityOfIdentityCard=merchantOauth.getLegalPersonValidityOfIdentityCard();
            if (legalPersonValidityOfIdentityCard.split("\\|").length==1){
                idCardValidStartTime=legalPersonValidityOfIdentityCard.split(" - ")[0];
                idCardValidEndTime=legalPersonValidityOfIdentityCard.split(" - ")[1];
            }else{
                idCardValidStartTime=legalPersonValidityOfIdentityCard.split(" - ")[0];
                idCardValidEndTime= "长期";
            }
            WeiXinMicroBo microBo = new WeiXinMicroBo(
                    merchantOauth.getBusinessCode(),
                    merchantOauth.getLegalPersonIdentificationPortrait(),
                    merchantOauth.getLegalPersonIdCardNationalEmblem(),
                    merchantOauth.getLegalPersonName(),
                    merchantOauth.getLegalPersonIdentityCard(),
                    idCardValidStartTime,
                    idCardValidEndTime,
                    merchantOauth.getSettlementAccountName(),
                    merchantOauth.getDepositBank(),
                    merchantOauth.getBankAddressCode(),
                    merchantOauth.getAccountOpeningBranch(),
                    merchantOauth.getSettlementAccountBankCard(),
                    merchantOauth.getStoreName(),
                    merchantOauth.getStoreAddressCode(),
                    merchantOauth.getStoreStreet(),
                    merchantOauth.getMerchantsDoorHead(),
                    merchantOauth.getIndoorPic(),
                    merchantOauth.getMerchantShortname(),
                    merchantOauth.getServiceTel(),
                    merchantOauth.getProductDesc(),
                    "0.6%",
                    merchantOauth.getLegalPersonName(),
                    merchantOauth.getLegalPersonPhone(),
                    merchantOauth.getPrincipalEmail()
            );
            System.out.println(JSON.toJSONString(microBo));
            EXPayResult baseResult = WeiXinMicroMerchantServicesUtil.microSubmit(microBo);
            if (baseResult.isSuccess()){
                String merchantNo=merchantUserService.selectByPrimaryKey(merchantOauth.getMerchantUserId()).getMerchantNo();
                MerchantWeixinSignExample merchantWeixinSignExample=new MerchantWeixinSignExample();
                merchantWeixinSignExample.createCriteria().andMerchantNoEqualTo(merchantNo).andBusinessCodeEqualTo(merchantOauth.getBusinessCode());
                if (merchantWeixinSignService.countByExample(merchantWeixinSignExample)==0){
                    Map jsonObject=(Map) baseResult.getData();
                    MerchantWeixinSign merchantWeixinSign=new MerchantWeixinSign();
                    merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                    merchantWeixinSign.setGmtCreate(System.currentTimeMillis());
                    merchantWeixinSign.setIsDeleted(AdminConstants.NO);
                    merchantWeixinSign.setMerchantNo(merchantNo);
                    merchantWeixinSign.setStatus(Byte.valueOf("0"));
                    merchantWeixinSign.setBusinessCode(merchantOauth.getBusinessCode());
                    merchantWeixinSign.setApplymentId(jsonObject.get("applyment_id").toString());
                    merchantWeixinSignService.insertSelective(merchantWeixinSign);
                }



            }
            return new AdminResult(baseResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "系统错误:" + e.getLocalizedMessage(), null);

        }
    }
    @ApiOperation(value = "获取小微商户状态")
    @RequestMapping(value = "/{applymentId}/microGetState", method = RequestMethod.POST)
    @ResponseBody
    public Object microGetState(@PathVariable("applymentId") String applymentId, HttpServletRequest request) throws Exception {
        EXPayResult baseResult=WeiXinMicroMerchantServicesUtil.microGetState(applymentId);
        if (baseResult.isSuccess()){
            /**
             * AUDITING:审核中
             *
             * REJECTED:已驳回
             *
             * FROZEN:已冻结
             *
             * TO_BE_SIGNED:
             *
             * FINISH:
             */
            System.out.println(baseResult);
            Map <String,String>map=(Map<String, String>) baseResult.getData();
            String applyMentState=map.get("applyment_state");
            MerchantWeixinSignExample merchantWeixinSignExample=new MerchantWeixinSignExample();
            merchantWeixinSignExample.createCriteria().andApplymentIdEqualTo(applymentId);
            List<MerchantWeixinSign>merchantWeixinSigns=merchantWeixinSignService.selectByExample(merchantWeixinSignExample);
            MerchantWeixinSign merchantWeixinSign=merchantWeixinSigns.get(0);
            if ("REJECTED".equals(applyMentState)){
                /**
                 * 已驳回
                 */
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("3"));
                baseResult.setSuccess(false);
                baseResult.setMessage(map.get("applyment_state_desc"));
                merchantWeixinSignService.deleteByExample(merchantWeixinSignExample);
                JSONArray auditDetail=JSONObject.parseObject(map.get("audit_detail").toString()).getJSONArray("audit_detail");
                for (Integer i=0;i<auditDetail.size();i++){
                    baseResult.setMessage(baseResult.getData()+","+(auditDetail.getJSONObject(i).getString("reject_reason")));
                }
            }else if("TO_BE_SIGNED".equals(applyMentState)){
                /**
                 * 待签约
                 */
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("4"));
                baseResult.setData(map.get("sign_url"));
            }else if("AUDITING".equals(applyMentState)){
                /**
                 * 审核中
                 */
                baseResult.setSuccess(false);
                baseResult.setMessage("审核中");
            }else if("FINISH".equals(applyMentState)){
                /**
                 * 完成
                 */
                baseResult.setMessage("签约完成！");
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("5"));
                merchantWeixinSign.setMchId(map.get("sub_mch_id"));
                baseResult.setSuccess(false);

            }
            merchantWeixinSignService.updateByPrimaryKeySelective(merchantWeixinSign);

        }
        return  baseResult;
    }
    @ApiOperation(value = "小微商户升级")
    @RequestMapping(value = "/{id}/microSubmitUpGrade", method = RequestMethod.POST)
    @ResponseBody
    public AdminResult doMicroSubmitUpGrade(@PathVariable("id") Long id,HttpServletRequest request) {
        try {

            MerchantOauth merchantOauth = merchantOauthService.selectByPrimaryKey(id);
            MerchantWeixinSignExample merchantWeixinSignExample=new MerchantWeixinSignExample();
            merchantWeixinSignExample.createCriteria().andBusinessCodeEqualTo(merchantOauth.getBusinessCode());
            List<MerchantWeixinSign>merchantWeixinSigns=merchantWeixinSignService.selectByExample(merchantWeixinSignExample);
            if (merchantWeixinSigns.isEmpty()){
                return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "微信商户还未通过审核", null);

            }
            String savePath = request.getSession().getServletContext().getRealPath(
                    "/")
                    + "/upload/micro/oauth/" + merchantOauth.getMerchantUserId() + "/";
            File tempDirPath = new File(savePath);
            if (!tempDirPath.exists()) {
                tempDirPath.mkdirs();
            }

            EXPayResult imageResult= WeiXinMicroMerchantServicesUtil.uploadWxPicture(ImageUtil.downloadPicture(merchantOauth.getBusinessLicense(), savePath));
            if (!imageResult.isSuccess()){
                return  new AdminResult(imageResult);
            }
            merchantOauth.setBusinessLicense(imageResult.getData().toString());


            String businessStartTime="";
            String businessEndTime="";
            String validityOfBusinessLicense=merchantOauth.getValidityOfBusinessLicense();
            if (validityOfBusinessLicense.split("\\|").length==1){
                businessStartTime=validityOfBusinessLicense.split(" - ")[0];
                businessEndTime=validityOfBusinessLicense.split(" - ")[1];
            }else{
                businessStartTime=validityOfBusinessLicense.split(" - ")[0];
                businessEndTime= "长期";
            }
            WeiXinMicroBo microBo=new WeiXinMicroBo(
                    merchantOauth.getMerchantShortname(),
                    "719",
                    merchantWeixinSigns.get(0).getMchId(),
                    merchantOauth.getOrganizationType(),
                    merchantOauth.getBusinessLicense(),
                    merchantOauth.getBusinessLicenseRegistrationName(),
                    merchantOauth.getStoreName(),
                    merchantOauth.getCompanyAddress(),
                    merchantOauth.getLegalPersonName(),
                    businessStartTime,
                    businessEndTime,
                    merchantOauth.getBusinessLicenceType(),
                    "[1721]"//1837
            );
            EXPayResult baseResult = WeiXinMicroMerchantServicesUtil.microSubmitUpGrade(microBo);
            System.out.println(baseResult);

            if (baseResult.isSuccess()){



            }
            return new AdminResult(baseResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new AdminResult(Boolean.FALSE, AdminConstants.FAILE, "系统错误:" + e.getLocalizedMessage(), null);

        }
    }

    @ApiOperation(value = "获取小微商户升级状态")
    @RequestMapping(value = "/{subMchId}/microGetUpGradeState", method = RequestMethod.POST)
    @ResponseBody
    public Object microGetUpGradeState(@PathVariable("subMchId") String subMchId, HttpServletRequest request) throws Exception {
        EXPayResult baseResult=WeiXinMicroMerchantServicesUtil.microGetUpGradeState(subMchId);
        if (baseResult.isSuccess()){
            /**
             CHECKING:资料校验中
             ACCOUNT_NEED_VERIFY：待账户验证
             AUDITING:审核中
             REJECTED:已驳回
             NEED_SIGN:待签约
             FINISH:完成
             FROZEN:已冻结
             */
            System.out.println(baseResult);
            Map <String,String>map=(Map<String, String>) baseResult.getData();
            String applyMentState=map.get("applyment_state");
            MerchantWeixinSignExample merchantWeixinSignExample=new MerchantWeixinSignExample();
            merchantWeixinSignExample.createCriteria().andMchIdEqualTo(subMchId);
            List<MerchantWeixinSign>merchantWeixinSigns=merchantWeixinSignService.selectByExample(merchantWeixinSignExample);
            MerchantWeixinSign merchantWeixinSign=merchantWeixinSigns.get(0);
            if ("REJECTED".equals(applyMentState)){
                /**
                 * 已驳回
                 */
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("3"));
                baseResult.setSuccess(false);
                baseResult.setMessage(map.get("applyment_state_desc"));
                merchantWeixinSignService.deleteByExample(merchantWeixinSignExample);
                JSONArray auditDetail=JSONObject.parseObject(map.get("audit_detail").toString()).getJSONArray("audit_detail");
                for (Integer i=0;i<auditDetail.size();i++){
                    baseResult.setMessage(baseResult.getData()+","+(auditDetail.getJSONObject(i).getString("reject_reason")));
                }
            }else if("CHECKING".equals(applyMentState)){
                /**
                 * 资料校验中
                 */
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("6"));
            }else if("ACCOUNT_NEED_VERIFY".equals(applyMentState)){
                /**
                 * 待账户验证
                 */
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("7"));
            }else if("AUDITING".equals(applyMentState)){
                /**
                 * 审核中
                 */
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("8"));
            }else if("NEED_SIGN".equals(applyMentState)){
                /**
                 * 待签约
                 */
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("9"));
                baseResult.setData(map.get("sign_url"));
            }else if("FINISH".equals(applyMentState)){
                /**
                 * 完成
                 */
                baseResult.setMessage("签约完成！");
                merchantWeixinSign.setGmtModified(System.currentTimeMillis());
                merchantWeixinSign.setStatus(Byte.valueOf("10"));
                baseResult.setSuccess(false);

            }
            merchantWeixinSignService.updateByPrimaryKeySelective(merchantWeixinSign);

        }
        return  baseResult;
    }


    public static void main(String[] args) throws Exception {
        String s="2019-07-30 - 2019-09-21";
        System.out.println(s.split("\\|").length);
    }


}
